﻿/**
 * Created by arvin on 2017/3/28.
 */
'use strict'
var Bearcat = require('bearcat');
var Async = require("async")

module.exports = function () {

    return Bearcat.getBean(
        {
            id:"get-wechat",
            func:wechat,
            props:[
                { name : "app","ref":"application"}
            ]
        }
    );
}

function wechat() {
    this.app = null;
}

var CheckMsgInvaild = function (msg) {

    if ( msg.params.UID == undefined
        || msg.params.MotionDevice == undefined
        || msg.params.MotionName == undefined
        || msg.params.TimeLength == undefined
        || msg.params.WechatName == undefined
        || msg.params.SKU == undefined)
        return false;
    return true;
}

wechat.prototype.handle = function (msg,next) {

    if(!CheckMsgInvaild( msg))
    {
        console.error("test_111111");
        next(null,{code:101,msg:"参数不对"});
        return;
    }

    var motiondevice = msg.params.MotionDevice;
    var device = this.app.getComponent("dao").getConnection().model("MotionDevices");
    var wechatData = this.app.getComponent("dao").getConnection().model("wechatMsg");
    Async.waterfall(
        [
            function (cb) { // 这里查询device
                device.invalidate(motiondevice,function (invalid) {
                    if(!invalid)
                    {
                        next(null,{code:104,msg:"con't find this device id"});
                    }
                    else
                        cb();
                })
            },
            function (cb) { // device 有效，查询是否在使用中
                device.GetMotionState(motiondevice,function (state) {
                    if(state == 1) // 表示设备正在使用
                    {
                        next(null,{code:103,msg:"设备正在使用"});
                        return;
                    }
                    else if( state == 99 )
                    {
                        next(null,{code:103,msg:"设备正在维修"});
                        return;
                    }
                    cb();
                })
            },
            function () { // device 有效，且设备空闲，将数据插入到表里
                wechatData.insertItem(
                    {
                        UID: msg.params.UID, // 丁哲提供
                        MotionDevice: msg.params.MotionDevice,// 二维码自带数据
                        MotionName: msg.params.MotionName,// 二维码自带数据(如果都是Adm，就没有意义)
                        WechatName: msg.params.WechatName,// 丁哲提供
                        TimeLength: msg.params.TimeLength,// 时间长度 单位是分钟丁哲提供
                        TurnLength: msg.params.TurnLength,// 圈数，暂时不考虑
                        SKU: msg.params.SKU,// 商品编号
                    },
                    function (result) {
                        console.error("ID有效，我这里成功接收到消息 :" +result);
                        next(null,{code:1,msg:"insert"});
                    }

                );
            }
        ],function (e) {
            next(null,{code:102,msg:e});
        }
    );
}
